package org.boyan.modules.cgform.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.boyan.common.system.api.ISysBaseAPI;
import org.boyan.common.system.query.MatchTypeEnum;
import org.boyan.common.system.util.JeecgDataAutorUtils;
import org.boyan.common.system.vo.LoginUser;
import org.boyan.common.system.vo.SysPermissionDataRuleModel;
import org.boyan.common.util.oConvertUtils;
import org.boyan.modules.auth.service.IOnlAuthDataService;
import org.boyan.modules.cgform.entity.OnlCgformField;
import org.boyan.modules.cgform.entity.OnlCgformHead;
import org.boyan.modules.cgform.model.c;
import org.boyan.modules.cgform.model.e;
import org.boyan.modules.cgform.service.IOnlCgformFieldService;
import org.boyan.modules.cgform.service.IOnlCgformHeadService;
import org.boyan.modules.cgform.service.IOnlineJoinQueryService;
import org.boyan.modules.cgform.util.b;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("onlineJoinQueryService")
public class j implements IOnlineJoinQueryService {
    private static final Logger a = LoggerFactory.getLogger(j.class);

    @Autowired
    IOnlCgformFieldService onlCgformFieldService;

    @Autowired
    IOnlCgformHeadService onlCgformHeadService;

    @Autowired
    private IOnlAuthDataService onlAuthDataService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Override
    public Map<String, Object> pageList(OnlCgformHead head, Map<String, Object> params, boolean ignoreSelectSubField) {
        LoginUser loginUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        List<c> list = a(head, loginUser.getId());
        JSONArray jSONArray = b.c(params);
        MatchTypeEnum matchTypeEnum = b.d(params);
        StringBuilder stringBuilder = new StringBuilder();
        boolean bool = true;
        String str1 = "";
        boolean bool1 = false;
        StringBuffer stringBuffer1 = new StringBuffer();
        StringBuffer stringBuffer2 = new StringBuffer();
        ArrayList<String> arrayList = new ArrayList<>();
        ArrayList<e> arrayList1 = new ArrayList<>();
        HashMap<Object, Object> hashMap1 = new HashMap<>();
        HashMap<Object, Object> hashMap2 = new HashMap<>();
        List<OnlCgformField> list1 = new ArrayList<>();
        for (c c : list) {
            List<OnlCgformField> list2 = c.getSelectFieldList();
            String str6 = c.getAlias();
            String str7 = str6 + ".";
            String str8 = " " + str6 + " ";
            String str9 = c.getTableName();
            if (c.a() || !ignoreSelectSubField)
                a(str7, c.a(), list2, arrayList, (Map)hashMap1);
            List<OnlCgformField> list3 = c.getAllFieldList();
            List<SysPermissionDataRuleModel> list4 = c.getAuthList();
            if (!bool1 && list4 != null && list4.size() > 0) {
                JeecgDataAutorUtils.installUserInfo(this.sysBaseAPI.getCacheUser(loginUser.getUsername()));
                bool1 = true;
            }
            String str10 = b.a(list3, params, null, list4, str7, str9 + "@");
            stringBuffer2.append(str10);
            if (ignoreSelectSubField && c.a())
                list1 = list2;
            if (c.a()) {
                stringBuffer1.append(" FROM " + b.f(str9) + str8);
                str1 = str7;
            } else {
                hashMap2.put(str6, str9);
                if ((list2 == null || list2.size() == 0) && "".equals(str10))
                    continue;
                stringBuffer1.append(" JOIN ");
                stringBuffer1.append(b.f(str9));
                stringBuffer1.append(str8);
                stringBuffer1.append(" ON ");
                stringBuffer1.append(str7);
                stringBuffer1.append(c.getJoinField());
                stringBuffer1.append("=");
                stringBuffer1.append(str1);
                stringBuffer1.append(c.getMainField());
            }
            a(params, c.a(), str9, str7, list3, arrayList1);
            bool = a(stringBuilder, jSONArray, matchTypeEnum, str7, str9, list3, c.a(), bool);
        }
        String str2 = a(arrayList, (Map)hashMap1, (Map)hashMap2);
        String str3 = a(stringBuilder);
        String str4 = a(arrayList1);
        String str5 = "SELECT " + str2 + stringBuffer1.toString() + " where 1=1  " + stringBuffer2.toString() + str3 + str4;
        a.info("---Online查询sql :>> " + str5);
        HashMap<Object, Object> hashMap3 = new HashMap<>();
        int integer = (params.get("pageSize") == null) ? 10 : Integer.parseInt(params.get("pageSize").toString());
        if (integer == -521) {
            List<Map<String, Object>> list2 = this.onlCgformFieldService.queryListBySql(str5);
            if (list2 == null || list2.size() == 0) {
                hashMap3.put("total", 0);
            } else {
                hashMap3.put("total", list2.size());
                if (ignoreSelectSubField)
                    list2 = b(list2);
                hashMap3.put("records", b.a(list2, hashMap2.values()));
            }
            if (ignoreSelectSubField)
                hashMap3.put("fieldList", list1);
        } else {
            Integer integer1 = (params.get("pageNo") == null) ? 1 : Integer.parseInt(params.get("pageNo").toString());
            IPage iPage = this.onlCgformFieldService.selectPageBySql(str5, integer1, (int) integer);
            hashMap3.put("total", iPage.getTotal());
            List<Map<String, Object>> list2 = iPage.getRecords();
            if (ignoreSelectSubField)
                list2 = b(list2);
            hashMap3.put("records", b.a(list2, hashMap2.values()));
        }
        return (Map)hashMap3;
    }

    @Override
    public Map<String, Object> pageList(OnlCgformHead head, Map<String, Object> params) {
        return pageList(head, params, false);
    }

    private String a(List<String> paramList, Map<String, Integer> paramMap, Map<String, String> paramMap1) {
        ArrayList<String> arrayList = new ArrayList<>();
        for (String str1 : paramList) {
            String[] arrayOfString = str1.split("\\.");
            String str2 = arrayOfString[0];
            if ("a".equals(str2)) {
                arrayList.add(str1);
                continue;
            }
            String str3 = arrayOfString[1];
            int i = paramMap.get(str3);
            if (i > 1) {
                String str = paramMap1.get(str2);
                arrayList.add(str1 + " " + str + "_" + str3);
                continue;
            }
            arrayList.add(str1);
        }
        return String.join(",", arrayList);
    }

    private void a(String paramString, boolean paramBoolean, List<OnlCgformField> paramList, List<String> paramList1, Map<String, Integer> paramMap) {
        if (paramList == null || paramList.size() == 0) {
            if (paramBoolean)
                paramList1.add(paramString + "id");
        } else {
            int i = paramList.size();
            for (OnlCgformField onlCgformField : paramList) {
                String str = onlCgformField.getDbFieldName();
                if (!"id".equals(str)) {
                    if ("cat_tree".equals(onlCgformField.getFieldShowType()) && oConvertUtils.isNotEmpty(onlCgformField.getDictText()))
                        paramList1.add(paramString + onlCgformField.getDictText());
                    paramList1.add(paramString + str);
                    paramMap.merge(str, 1, (a1, b) -> b + a1);
                }
            }
            paramList1.add(paramString + "id");
            paramMap.put("id", 2);
        }
    }

    private c a(OnlCgformHead paramOnlCgformHead, int paramInt, boolean paramBoolean) {
        String str1 = paramOnlCgformHead.getId();
        String str2 = paramOnlCgformHead.getTableName();
        c c = new c(str2, str1, paramBoolean);
        List<OnlCgformField> list = a(str1);
        List<OnlCgformField> list1 = this.onlCgformFieldService.queryAvailableFields(str1, str2, true, list, null);
        c.setAllFieldList(list);
        c.setSelectFieldList(list1);
        c.setAliasByIntValue(paramInt);
        if (!paramBoolean)
            for (OnlCgformField onlCgformField : list) {
                if (oConvertUtils.isNotEmpty(onlCgformField.getMainField()) && oConvertUtils.isNotEmpty(onlCgformField.getMainTable())) {
                    c.setMainField(onlCgformField.getMainField());
                    c.setJoinField(onlCgformField.getDbFieldName());
                    break;
                }
            }
        return c;
    }

    private List<c> a(OnlCgformHead paramOnlCgformHead, String paramString) {
        byte b = 97;
        ArrayList<c> arrayList = new ArrayList<>();
        c c = a(paramOnlCgformHead, b++, true);
        List list = this.onlAuthDataService.queryUserOnlineAuthData(paramString, paramOnlCgformHead.getId());
        c.setAuthList(list);
        arrayList.add(c);
        Integer integer = paramOnlCgformHead.getTableType();
        if (integer != null && integer == 2) {
            String str = paramOnlCgformHead.getSubTableStr();
            if (str != null && !"".equals(str)) {
                String[] arrayOfString = str.split(",");
                for (String str1 : arrayOfString) {
                    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getOne(
                            new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName, str1));
                    if (onlCgformHead != null) {
                        c c1 = a(onlCgformHead, b++, false);
                        List list1 = this.onlAuthDataService.queryUserOnlineAuthData(paramString, onlCgformHead.getId());
                        c1.setAuthList(list1);
                        arrayList.add(c1);
                    }
                }
            }
        }
        return arrayList;
    }

    private Map<String, List<OnlCgformField>> a(OnlCgformHead paramOnlCgformHead, Map<String, String> paramMap) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        paramMap.put(paramOnlCgformHead.getTableName(), paramOnlCgformHead.getId());
        List<OnlCgformField> list = a(paramOnlCgformHead.getId());
        hashMap.put(paramOnlCgformHead.getTableName(), list);
        Integer integer = paramOnlCgformHead.getTableType();
        if (integer != null && integer == 2) {
            String str = paramOnlCgformHead.getSubTableStr();
            if (str != null && !"".equals(str)) {
                String[] arrayOfString = str.split(",");
                for (String str1 : arrayOfString) {
                    OnlCgformHead onlCgformHead = (OnlCgformHead)this.onlCgformHeadService.getOne(new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName, str1));
                    if (onlCgformHead != null) {
                        paramMap.put(onlCgformHead.getTableName(), onlCgformHead.getId());
                        List<OnlCgformField> list1 = a(onlCgformHead.getId());
                        hashMap.put(onlCgformHead.getTableName(), list1);
                    }
                }
            }
        }
        return (Map)hashMap;
    }

    private List<OnlCgformField> a(String paramString) {
        LambdaQueryWrapper<OnlCgformField> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OnlCgformField::getCgformHeadId, paramString);
        lambdaQueryWrapper.orderByAsc(OnlCgformField::getOrderNum);
        return this.onlCgformFieldService.list(lambdaQueryWrapper);
    }

    private void a(Map<String, Object> paramMap, boolean paramBoolean, String paramString1, String paramString2, List<OnlCgformField> paramList, List<e> paramList1) {
        Object object = paramMap.get("column");
        if (object != null && !"id".equals(object.toString())) {
            String str1 = object.toString();
            Object object1 = paramMap.get("order");
            String str2 = "desc";
            if (object1 != null)
                str2 = object1.toString();
            if (paramBoolean) {
                if (b.c(str1, paramList)) {
                    e e = new e(str1, str2);
                    e.setAlias(paramString2);
                    paramList1.add(e);
                }
            } else if (str1.startsWith(paramString1)) {
                String str = str1.replaceFirst(paramString1 + "_", "");
                if (b.c(str, paramList)) {
                    e e = new e(str, str2);
                    e.setAlias(paramString2);
                    paramList1.add(e);
                }
            }
        } else {
            for (OnlCgformField onlCgformField : paramList) {
                if ("1".equals(onlCgformField.getSortFlag())) {
                    String str = onlCgformField.getFieldExtendJson();
                    e e = new e(onlCgformField.getDbFieldName());
                    e.setAlias(paramString2);
                    if (str != null && !"".equals(str)) {
                        JSONObject jSONObject = JSON.parseObject(str);
                        String str1 = jSONObject.getString("orderRule");
                        if (str1 != null && !"".equals(str1))
                            e.setRule(str1);
                    }
                    paramList1.add(e);
                }
            }
        }
    }

    private String a(List<e> paramList) {
        if (paramList.size() == 0) {
            e e = org.boyan.modules.cgform.model.e.a("a.");
            paramList.add(e);
        }
        ArrayList<String> arrayList = new ArrayList<>();
        for (e e : paramList) {
            String str = e.getRealSql();
            arrayList.add(str);
        }
        return " ORDER BY " + String.join(",", arrayList);
    }

    private String a(StringBuilder paramStringBuilder) {
        String str = paramStringBuilder.toString();
        if ("".equals(str))
            return "";
        return " AND (" + str + ") ";
    }

    private boolean a(StringBuilder paramStringBuilder, JSONArray paramJSONArray, MatchTypeEnum paramMatchTypeEnum, String paramString1, String paramString2, List<OnlCgformField> paramList, boolean paramBoolean1, boolean paramBoolean2) {
        boolean bool = paramBoolean2;
        if (paramJSONArray != null)
            for (byte b = 0; b < paramJSONArray.size(); b++) {
                JSONObject jSONObject = paramJSONArray.getJSONObject(b);
                String str = jSONObject.getString("field");
                String[] arrayOfString = str.split(",");
                if (arrayOfString.length == 1) {
                    if (paramBoolean1 && org.boyan.modules.cgform.util.b.c(str, paramList)) {
                        String str1 = paramString1 + str;
                        org.boyan.modules.cgform.util.b.a(paramStringBuilder, str1, jSONObject, paramMatchTypeEnum, null, bool);
                        bool = false;
                    }
                } else {
                    String str1 = arrayOfString[1];
                    if (paramString2.equalsIgnoreCase(arrayOfString[0]) &&
                            org.boyan.modules.cgform.util.b.c(str1, paramList)) {
                        String str2 = paramString1 + str1;
                        org.boyan.modules.cgform.util.b.a(paramStringBuilder, str2, jSONObject, paramMatchTypeEnum, null, bool);
                        bool = false;
                    }
                }
            }
        return bool;
    }

    private List<Map<String, Object>> b(List<Map<String, Object>> paramList) {
        HashMap<String, Object> hashMap = new HashMap<>();
        for (Map<String, Object> map : paramList) {
            String str = map.get("id").toString();
            hashMap.putIfAbsent(str, map);
        }
        return new ArrayList(hashMap.values());
    }
}
